package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型: pre,post,routing,error
    @Override
    public String filterType() {
        //return "pre"
        return FilterConstants.PRE_TYPE;
    }

    //过滤器插入的位置
    //第五个过滤器中在上下文对象添加了 serviceId
    //在后面过滤器中才能访问 serviceId
    @Override
    public int filterOrder() {
        return 6;
    }

    //对用户请求进行判断,是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*
        * 只对item-service调用进行过滤
        * 如果调用 user-service 或 order-service,不执行过滤代码
        */
        //获得调用的服务id
        RequestContext ctx=RequestContext.getCurrentContext();
        String serviceId=(String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        /*
        * http://localhost:3001/item-service/y45y45y4y  阻止访问
        * http://localhost:3001/item-service/y45y45y4y?token=3t3t34t    允许访问
        */
        //获得request对象
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();

        // 接收token参数
        String token=request.getParameter("token");

        //如果没有token,阻止访问,并直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            //阻止继续访问
            ctx.setSendZuulResponse(false);

            //JsonResult {code:401,msg:not login,data:null}
            String json=JsonResult.err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("not login")
                    .toString();
            ctx.addZuulResponseHeader("Content-Type",
                    "application/json;charset=UTF-8" );
            ctx.setResponseBody(json);
        }
       return null; //返回值没有任何作用
    }
}
